package hot100.logos21To30;

import hot100.datastruct.ListNode;

/**
 * @author logos
 * date 2025/7/12 13:38
 * @version v1.0
 * @Package hot100
 */
public class logos28 {

    /**
     * 28.两数相加
     * https://leetcode.cn/problems/add-two-numbers/submissions/643279088/?envType=study-plan-v2&envId=top-100-liked
     */

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode ans = null;
        ListNode cur = null;
        int carry = 0;
        for (int sum = 0, val = 0;
             l1 != null || l2 != null;
             l1 = l1 == null ? null : l1.next,
             l2 = l2 == null ? null : l2.next
        ) {
            sum = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry;
            val = sum % 10;
            carry = sum / 10;
            if (ans == null) {
                ans = new ListNode(val);
                cur = ans;
            } else {
                cur.next = new ListNode(val);
                cur = cur.next;
            }
        }
        if (carry > 0) {
            cur.next = new ListNode(carry);
        }
        return ans;
    }
}
